<?php
function rebuildArr($arr1,$arr2=[]){
    $tmp_arr1=$arr1;
    if(empty($arr2)){
        $tmp_arr2=$arr1;
    }else{
        $tmp_arr2=$arr2;
    }
    foreach ($tmp_arr1 as $key => $value) {
        foreach ($tmp_arr2 as $key1 => $value1) {
            if($value['id']==$value1['pid']){
                $arr1[$key]['son'][]=$value1;
            }
        }
        if(isset($arr1[$key]['son'])){
            $arr1[$key]['son']=rebuildArr($arr1[$key]['son'],$arr1);
        }
    }

    return $arr1;
}
function rebuildArr1($arr1,$arr2=[]){
    $arr=rebuildArr($arr1,$arr2=[]);
    foreach ($arr as $key=> $item) {
        if ($item['pid']!=0)
            unset($arr[$key]);
    }
    return $arr;
}

function caidan($permission_id){
    $superid=5;
    $role_id=session('role_id');
    $db=db('permission');
    if($role_id!=$superid){
        $db=$db->where(['id'=>['in',$permission_id]]);
    }
    $caidan=$db->where(['type'=>0])->order('desc')->select();
    $tmp_caidan=$caidan;
    foreach ($tmp_caidan as $key1 => $value1) {
        foreach ($tmp_caidan as $key2 => $value2) {
            if($value1['id']==$value2['pid']){
                $caidan[$key1]['son'][]=$value2;
                unset($caidan[$key2]);
            }         
        }
        
    }
    return $caidan;
}